package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

//订单定时处理类
//1超时未支付的订单
//触发时间 每分钟
//处理逻辑 查询满足条件的订单 修改订单的状态为 已取消
//2已完成一直处在派送中的订单
@Component
@Slf4j
public class OrderTask {
    @Autowired
    OrderMapper orderMapper;

    @Scheduled(cron = "0 * * * * ?")
    public void handleOrder() {
        log.info("订单定时任务开始执行");
        //查询满足条件的订单 超时未支付的订单
        LocalDateTime now = LocalDateTime.now().minusMinutes(15);
        List<Orders> orders = orderMapper.getStatussAndOrderTime(Orders.PENDING_PAYMENT, now);
        //修改订单的状态为 已取消
        if (orders != null && orders.size() > 0) {
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason(MessageConstant.ORDER_OUTTIME_CANCEL);
                //更新订单
                orderMapper.update(order);
            }
        }
    }

    //2已完成一直处在派送中的订单
    //任务的触发时间: 凌晨3点触发
     @Scheduled(cron = "0 0 3 * * ?")    //任务的触发时间: 凌晨3点触发
//    @Scheduled(cron = "0/5 * * * * ?")//方便测试 每隔5秒测试一次
    public void handelComoledInDelivery() {
        log.info("处理已完成一直处在派送中的订单");
        LocalDateTime now = LocalDateTime.now().minusHours(3);
        List<Orders> orders = orderMapper.getStatussAndOrderTime(Orders.DELIVERY_IN_PROGRESS, now);
        //修改订单的状态为 已取消
        if (orders != null && orders.size() > 0) {
            for (Orders order : orders) {
                order.setStatus(Orders.COMPLETED);
                order.setCancelTime(LocalDateTime.now());
                //更新订单
                orderMapper.update(order);
            }
        }
    }
}
